<?php


namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use OSS\OssClient;
use App\Services\UploadService;
use App\Services\CommonService;
use App\Services\BaiduService;
use App\Services\Qrcodedecoder;
use App\Models\Users;
use App\Models\Blackdomains;
use App\Http\Controllers\Controller;
use Log;

class UploadController extends Controller
{
    public function getAccessToken()
    {
        header('Access-Control-Allow-Origin: *'); 
        return UploadService::getAccessToken();
    }

    public function aliossUploadBack(Request $request)
    {
        $authorizationBase64 = "";
        $pubKeyUrlBase64 = "";
        if (isset($_SERVER['HTTP_AUTHORIZATION'])) $authorizationBase64 = $_SERVER['HTTP_AUTHORIZATION'];
        if (isset($_SERVER['HTTP_X_OSS_PUB_KEY_URL'])) $pubKeyUrlBase64 = $_SERVER['HTTP_X_OSS_PUB_KEY_URL'];
        if ($authorizationBase64 == '' || $pubKeyUrlBase64 == ''){
            header("http/1.1 403 Forbidden");
            exit();
        }

        // 2.获取OSS的签名
        $authorization = base64_decode($authorizationBase64);

        // 3.获取公钥
        $pubKeyUrl = base64_decode($pubKeyUrlBase64);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $pubKeyUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $pubKey = curl_exec($ch);
        if ($pubKey == ""){
            exit();
        }

        // 4.获取回调body
        $body = file_get_contents('php://input');

        // 5.拼接待签名字符串
        $authStr = '';
        $path = $_SERVER['REQUEST_URI'];
        $pos = strpos($path, '?');
        if ($pos === false) {
            $authStr = urldecode($path)."\n".$body;
        } else {
            $authStr = urldecode(substr($path, 0, $pos)).substr($path, $pos, strlen($path) - $pos)."\n".$body;
        }

        // 6.验证签名
        $ok = openssl_verify($authStr, $authorization, $pubKey, OPENSSL_ALGO_MD5);
        if ($ok == 1)
        {
            header("Content-Type: application/json");
            $data = array("Status"=>"Ok");
            echo json_encode($data);
        } else {
            //header("http/1.1 403 Forbidden");
            exit();
        }
    }

    public function base64Upload(Request $request)
    {
        $key = $request->key;
        $users_id = $request->users_id;
        $sign = CommonService::aesDncrypt($request->sign);
        $token = CommonService::aesDncrypt($request->token);
        if ((time()-$token) < 3600) response()->json(["status"=>"error","code"=>"1001",'title'=>'图片上传失败',"msg"=>"接口异常,请稍后重试!"]);
        if ($key != $sign) response()->json(["status"=>"error","code"=>"1001",'title'=>'图片上传失败',"msg"=>"接口异常,请稍后重试!"]);
        $file = $request->images;
        if (empty($file)) return response()->json(["status"=>"error","code"=>"1001",'title'=>'未检测到图片信息',"msg"=>"请选择上传素材。"]);
        try {
            $entension = $file->getClientOriginalExtension();
            if (!in_array($entension, ["jpeg","png","gif","jpg"])) return response()->json(["status"=>"error","code"=>"1001",'title'=>'图片上传失败',"msg"=>"只支持上传JPG, PNG, GIF。"]);
            $filesize=$file->getSize();
            if ($filesize >= 300000) return response()->json(["status"=>"error","code"=>"1001",'title'=>'图片内存过大',"msg"=>"图片不能大于300KB。"]);
            $img = UploadService::uploadAlOss($file);
            //判断头像不能包含二维码
            if(!empty($request->avatar) && $request->avatar == 'avatar'){
                $qrcodedecode = Qrcodedecoder::judgeQrcode($img);
                if($qrcodedecode != 'other' && $qrcodedecode != 'empty'){
                    UploadService::deleteOssFile($img);
                    return response()->json(["status"=>"error","code"=>"1003","msg"=>'系统检测到图片包含二维码，请更换无二维码的图，或用全图模式','title'=>'头像处不能包含二维码']);
                }
            }
            //判断上传的二维码是否符合类型
            if(!empty($request->platfrom_type) && in_array($request->platfrom_type,[8,9,12])){
                $urltext = Qrcodedecoder::qrcodeDecoder($img);
                if(!empty($urltext)){
                    $blackdetail = Blackdomains::getBlackDetail($urltext);
                    if(!empty($blackdetail)){
                        // 禁用账户
                        Users::updateDsiable($users_id,2);
                        UploadService::deleteOssFile($img);
                        return response()->json(["status"=>"error","code"=>"1003","msg"=>'该二维码因多次违规已被加入黑名单，详情请联系客服处理','title'=>'账号已被封禁']);
                    }
                }
                $qrcodetype = ['识别到个人微信'=>'wechat','识别到企业微信'=>'work','识别到微信群'=>'group','识别到公众号'=>'official'];
                $qrcodedecode = Qrcodedecoder::judgeQrcode($img);
                if($request->platfrom_type== 8 && $request->platfrom == 3){
                    if($qrcodedecode != 'wechat'){
                        if (array_search($qrcodedecode,$qrcodetype)){
                            UploadService::deleteOssFile($img);
                            return response()->json(["status"=>"error","code"=>"1003","msg"=>'系统'.array_search($qrcodedecode,$qrcodetype).'二维码，请选择个人微信二维码上传','title'=>'选择的二维码类型未对应']);
                        }
                    }
                }elseif ($request->platfrom_type== 8 && $request->platfrom == 4) {
                    if($qrcodedecode != 'work'){
                        if (array_search($qrcodedecode,$qrcodetype)) {
                            UploadService::deleteOssFile($img);
                            return response()->json(["status"=>"error","code"=>"1003","msg"=>'系统'.array_search($qrcodedecode,$qrcodetype).'二维码，请选择企业微信二维码上传','title'=>'选择的二维码类型未对应']); 
                        }
                    }
                }elseif ($request->platfrom_type== 9) {
                    if($qrcodedecode != 'group'){
                        if (array_search($qrcodedecode,$qrcodetype)) {
                            UploadService::deleteOssFile($img);
                            return response()->json(["status"=>"error","code"=>"1003","msg"=>'系统'.array_search($qrcodedecode,$qrcodetype).'二维码，请选择微信群二维码上传','title'=>'选择的二维码类型未对应']); 
                        }
                    }
                }elseif($request->platfrom_type== 12){
                    if($qrcodedecode != 'official'){
                        if (array_search($qrcodedecode,$qrcodetype)) {
                            UploadService::deleteOssFile($img);
                            return response()->json(["status"=>"error","code"=>"1003","msg"=>'系统'.array_search($qrcodedecode,$qrcodetype).'二维码，请选择公众号二维码上传','title'=>'选择的二维码类型未对应']); 
                        }
                    }
                }
            }
            $baiducheck = BaiduService::baiduCheck($users_id,$img);
            if ($baiducheck != 1) {
                if ($baiducheck == 3) {
                    // 扣完信用分
                    Users::decrementUsersScode($users_id,3);
                    // 禁用账户
                    Users::updateDsiable($users_id,2);
                    return response()->json(["status"=>"error","code"=>"1002","msg"=>"您上传的照片可能包含色情/暴力/政治,账号已被封禁;如有疑问请联系企业微信客服！",'title'=>'图片上传失败']);
                }
                $creditScore = Users::getUsersScode($users_id);
                if ($creditScore->score <= 1) {
                    // 扣除信用分
                    Users::decrementUsersScode($users_id,1);
                    // 禁用账户
                    Users::updateDsiable($users_id,2);
                    return response()->json(["status"=>"error","code"=>"1002","msg"=>"您上传的照片违规超过3次,账号已被封禁;如有疑问请联系企业微信客服！",'title'=>'图片上传失败']);
                } else {
                    // 扣除信用分
                    Users::decrementUsersScode($users_id,1);
                    return response()->json(["status"=>"error","code"=>"1001","msg"=>"您上传的照片存在违规请更换,如还违规 ".($creditScore->score-1)." 次将被封号！",'title'=>'图片上传失败']);
                }
            }
            return response()->json(["status"=>"success","code"=>"1000","msg"=>"上传成功","url"=>$img,'title'=>'图片上传成功']);
        } catch (Exception $e) {
            return response()->json(["status"=>"error","code"=>"1001","msg"=>"上传失败,请联系客服。",'title'=>'图片上传失败']);
        }
    }

    public function uploadCheck(Request $request)
    {
        // 小程序端上传后再审核图片
        $images = json_decode($request->images);
        $checkStatus = 1;
        $creditScore = Users::getUsersScode($request->users_id);
        $score = $creditScore->score;
        $left_score = $creditScore->score;
        foreach ($images as $image) {
            $baiducheck = BaiduService::baiduCheck($request->users_id,$image);
            if ($baiducheck != 1) {
                if ($baiducheck == 3) {
                    $left_score -= 3;
                    $checkStatus = 3;
                    break;
                }
                if ($creditScore->score <= 1) {
                    $checkStatus = 2;
                    break;
                } else {
                    // 扣除信用分
                    $left_score -= 1;
                }
            }
        }
        if ($checkStatus != 1) {
            if ($checkStatus == 2) {
                // 扣除信用分
                Users::decrementUsersScode($request->users_id,1);
                return response()->json(["status"=>"error","code"=>"1002","msg"=>"您上传的照片违规超过3次,账号已被封禁;如有疑问请联系企业微信客服！"]);
            } else {
                // 扣除信用分
                Users::decrementUsersScode($request->users_id,3);
                return response()->json(["status"=>"error","code"=>"1002","msg"=>"您上传的照片可能包含色情/暴力/政治,账号已被封禁;如有疑问请联系企业微信客服！"]);
            }
            // 禁用账户
            Users::updateDsiable($request->users_id,2);
        } else {
            if ($left_score <= 0) {
                // 扣除信用分
                Users::decrementUsersScode($request->users_id,1);
                // 禁用账户
                Users::updateDsiable($request->users_id,2);
                return response()->json(["status"=>"error","code"=>"1002","msg"=>"您上传的照片违规超过3次,账号已被封禁;如有疑问请联系企业微信客服！"]);
            } elseif ($left_score < $score) {
                // 扣除信用分
                Users::decrementUsersScode($request->users_id,($score-$left_score));
                return response()->json(["status"=>"error","code"=>"1001","msg"=>"您上传的照片存在违规请更换,如还违规 ".$left_score." 次将被封号！"]);
            }
        }
        return response()->json(["status"=>"success","code"=>"1000","msg"=>"图片审核成功！"]);
    }
}